 // 获取元素
 const taskInput = document.getElementById('taskInput');
 const addTaskButton = document.getElementById('addTaskButton');
 const prioritySelect = document.getElementById('prioritySelect');
 const reminderInput = document.getElementById('reminderInput');
 const setReminderButton = document.getElementById('setReminderButton');
 const searchInput = document.getElementById('searchInput');
 const sortSelect = document.getElementById('sortSelect');
 const taskList = document.getElementById('taskList');
 const changeThemeButton = document.getElementById('changeThemeButton');
 const totalTasksCount = document.getElementById('totalTasksCount');
 const completedTasksCount = document.getElementById('completedTasksCount');
 const incompleteTasksCount = document.getElementById('incompleteTasksCount');

 // 任务数组，用于存储任务数据
 let tasks = [];
 let isDarkTheme = false;
 let reminderIntervals = {}; // 存储每个任务的定时器 ID

 // 加载本地存储的任务
 const loadTasks = () => {
   const storedTasks = localStorage.getItem('tasks');
   if (storedTasks) {
     tasks = JSON.parse(storedTasks);
     tasks.forEach((task, index) => {
       if (task.dueDate) {
         startCountdown(index, task.dueDate);
       }
     });
     renderTasks();
     updateTaskStatistics();
   }
 };

 // 保存任务到本地存储
 const saveTasks = () => {
   localStorage.setItem('tasks', JSON.stringify(tasks));
 };

// 添加任务
const addTask = () => {
  const taskName = taskInput.value.trim();
  if (taskName === '') return;
  const priority = prioritySelect.value;
  const customDateTimePicker = document.createElement('div');
  customDateTimePicker.id = 'customDateTimePicker';
  customDateTimePicker.style.display = 'none';
  const yearSelect = document.createElement('select');
  const monthSelect = document.createElement('select');
  const daySelect = document.createElement('select');
  const hourSelect = document.createElement('select');
  const minuteSelect = document.createElement('select');
  customDateTimePicker.appendChild(yearSelect);
  customDateTimePicker.appendChild(monthSelect);
  customDateTimePicker.appendChild(daySelect);
  customDateTimePicker.appendChild(hourSelect);
  customDateTimePicker.appendChild(minuteSelect);
  // 填充年份选项（这里简单示例为当前年份前后10年）
  const currentYear = new Date().getFullYear();
  for (let i = currentYear - 10; i <= currentYear + 10; i++) {
      const option = document.createElement('option');
      option.value = i;
      option.textContent = i;
      yearSelect.appendChild(option);
  }
  // 填充月份选项
  for (let i = 1; i <= 12; i++) {
      const option = document.createElement('option');
      option.value = i < 10? '0' + i : i;
      option.textContent = i < 10? '0' + i : i;
      monthSelect.appendChild(option);
  }
  // 填充日期选项（这里简单示例，可根据选择的月份进一步优化闰年等情况）
  for (let i = 1; i <= 31; i++) {
      const option = document.createElement('option');
      option.value = i < 10? '0' + i : i;
      option.textContent = i < 10? '0' + i : i;
      daySelect.appendChild(option);
  }
  // 填充小时选项
  for (let i = 0; i <= 23; i++) {
      const option = document.createElement('option');
      option.value = i < 10? '0' + i : i;
      option.textContent = i < 10? '0' + i : i;
      hourSelect.appendChild(option);
  }
  // 填充分钟选项
  for (let i = 0; i <= 59; i++) {
      const option = document.createElement('option');
      option.value = i < 10? '0' + i : i;
      option.textContent = i < 10? '0' + i : i;
      minuteSelect.appendChild(option);
  }
  const confirmButton = document.createElement('button');
  confirmButton.textContent = '确定';
  confirmButton.addEventListener('click', () => {
      const year = yearSelect.value;
      const month = monthSelect.value;
      const day = daySelect.value;
      const hour = hourSelect.value;
      const minute = minuteSelect.value;
      const dueDate = `${year}-${month}-${day}T${hour}:${minute}`;
      const newTask = { name: taskName, priority, completed: false, dueDate };
      tasks.push(newTask);
      saveTasks();
      taskInput.value = '';
      customDateTimePicker.style.display = 'none';
      renderTasks();
      updateTaskStatistics();
      if (dueDate) {
          const index = tasks.length - 1;
          startCountdown(index, newTask.dueDate);
      }
  });
  customDateTimePicker.appendChild(confirmButton);
  const datetimePickerPlaceholder = document.getElementById('datetimePickerPlaceholder');
  datetimePickerPlaceholder.appendChild(customDateTimePicker);
  customDateTimePicker.style.display = 'block';
};

 // 删除任务
 const deleteTask = (index) => {
   if (reminderIntervals[index]) {
     clearInterval(reminderIntervals[index]);
     delete reminderIntervals[index];
   }
   tasks.splice(index, 1);
   saveTasks();
   renderTasks();
   updateTaskStatistics();
 };

 // 切换任务状态
 const toggleTaskCompletion = (index) => {
   tasks[index].completed =!tasks[index].completed;
   saveTasks();
   renderTasks();
   updateTaskStatistics();
 };

 // 编辑任务
 const editTask = (index) => {
   const newName = prompt('编辑任务名称：', tasks[index].name);
   if (newName!== null && newName.trim()!== '') {
     tasks[index].name = newName;
     saveTasks();
     renderTasks();
   }
 };

// 渲染任务列表
const renderTasks = () => {
  taskList.innerHTML = '';
  let filteredTasks = tasks;
  const searchTerm = searchInput.value.trim().toLowerCase();
  if (searchTerm!== '') {
      filteredTasks = tasks.filter(task => task.name.toLowerCase().includes(searchTerm));
  }
  const sortBy = sortSelect.value;
  filteredTasks.sort((a, b) => {
      if (sortBy === 'name-asc') {
          return a.name.localeCompare(b.name);
      } else if (sortBy === 'name-desc') {
          return b.name.localeCompare(a.name);
      } else if (sortBy === 'priority-asc') {
          const priorityOrder = ['低', '中', '高'];
          return priorityOrder.indexOf(a.priority) - priorityOrder.indexOf(b.priority);
      } else if (sortBy === 'priority-desc') {
          const priorityOrder = ['低', '中', '高'];
          return priorityOrder.indexOf(b.priority) - priorityOrder.indexOf(a.priority);
      } else if (sortBy === 'dueDate-asc') {
          return new Date(a.dueDate) - new Date(b.dueDate);
      } else if (sortBy === 'dueDate-desc') {
          return new Date(b.dueDate) - new Date(a.dueDate);
      }
  });
  filteredTasks.forEach((task, index) => {
      const taskItem = document.createElement('div');
      taskItem.classList.add('task-item');
      if (task.completed) {
          taskItem.classList.add('completed');
      }
      let priorityIndicatorBox = document.createElement('div');
      // 优先级指示盒的逻辑
      let formattedDueDate = task.dueDate? new Date(task.dueDate).toLocaleString() : '无';
      taskItem.innerHTML = `<div class="priority-indicator-container">${priorityIndicatorBox.outerHTML}</div><span class="task-name">${task.name}</span> <span class="task-priority">优先级：${task.priority}</span> <span class="task-due-date">截止日期：${formattedDueDate}</span>
          <div class="action-buttons">
              <button class="delete-button">删除</button>
              <button class="toggle-button">${task.completed? '未完成' : '已完成'}</button>
              <button class="edit-button">编辑</button>
          </div>
          <div class="reminder-countdown-container"></div>`;
      taskList.appendChild(taskItem);
      const deleteButton = taskItem.querySelector('.delete-button');
      deleteButton.addEventListener('click', () => deleteTask(index));
      const toggleButton = taskItem.querySelector('.toggle-button');
      toggleButton.addEventListener('click', () => toggleTaskCompletion(index));
      const editButton = taskItem.querySelector('.edit-button');
      editButton.addEventListener('click', () => editTask(index));
      if (task.dueDate) {
          startCountdown(index, task.dueDate);
      }
  });
};

 // 设置任务提醒
 const setTaskReminder = () => {
   const dueDate = reminderInput.value;
   if (dueDate) {
     const index = tasks.length - 1;
     tasks[index].dueDate = dueDate;
     saveTasks();
     renderTasks();
     startCountdown(index, dueDate);
   }
 };

 // 开始倒计时
 const startCountdown = (index, dueDate) => {
   if (reminderIntervals[index]) {
     clearInterval(reminderIntervals[index]);
   }
   const targetDate = new Date(dueDate);
   const now = new Date();
   const timeDifference = targetDate.getTime() - now.getTime();
   if (timeDifference > 0) {
     let remainingSeconds = Math.floor(timeDifference / 1000);
     const countdownContainer = taskList.children[index].querySelector('.reminder-countdown-container');
     const countdownElement = document.createElement('span');
     countdownContainer.appendChild(countdownElement);
     reminderIntervals[index] = setInterval(() => {
      const days = Math.floor(remainingSeconds / (24 * 60 * 60));
      const hours = Math.floor((remainingSeconds % (24 * 60 * 60)) / (60 * 60));
      const minutes = Math.floor((remainingSeconds % (60 * 60)) / 60);
      const seconds = remainingSeconds % 60;
      let countdownText = `任务：${tasks[index].name}，剩余时间：${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
      if (remainingSeconds < 60) {
          countdownElement.style.color ='red'; // 剩余时间小于1分钟，文本变红
          if (remainingSeconds % 2 === 0) {
              countdownElement.style.visibility = 'hidden'; // 每隔1秒隐藏显示，实现闪烁效果
          } else {
              countdownElement.style.visibility = 'visible';
          }
      }
      countdownElement.textContent = countdownText;
      remainingSeconds--;
      if (remainingSeconds < 0) {
          clearInterval(reminderIntervals[index]);
          countdownElement.textContent = `任务：${tasks[index].name},你完成了吗？`;
      }
  }, 1000);
   } else {
     console.log('提醒时间已过。');
   }
 };

 // 切换主题
 const themes = {
  light: {
      backgroundColor: 'rgb(255, 234, 167)',
      textColor: '#333',
      buttonColor: '#fcddaf',
      inputBackgroundColor: '#fdebd6'
  },
  dark: {
      backgroundColor: '#333',
      textColor: 'rgb(255, 234, 167)',
      buttonColor: '#555',
      inputBackgroundColor: '#444'
  }
  };
  const changeTheme = () => {
    isDarkTheme =!isDarkTheme;
    const currentTheme = isDarkTheme? 'dark' : 'light';
    const body = document.body;
    const container = document.querySelector('.container');
    const allButtons = document.querySelectorAll('button');
    const allInputs = document.querySelectorAll('input');
    const allSelects = document.querySelectorAll('select');

    // 设置body的样式
    body.style.backgroundColor = currentTheme === 'dark'? '#888' : '#f4c680';
    body.style.color = themes[currentTheme].textColor;

    // 先设置容器的样式
    container.style.backgroundColor = themes[currentTheme].backgroundColor;
    container.style.color = themes[currentTheme].textColor;

    // 遍历并设置所有按钮的样式
    allButtons.forEach(button => {
        button.style.backgroundColor = themes[currentTheme].buttonColor;
        button.style.color = themes[currentTheme].textColor;
    });

    // 遍历并设置所有输入框和下拉列表的样式
    const allInputLikeElements = [...allInputs,...allSelects];
    allInputLikeElements.forEach(element => {
        element.style.backgroundColor = themes[currentTheme].inputBackgroundColor;
        element.style.color = themes[currentTheme].textColor;
    });
};

 // 更新任务统计信息
 const updateTaskStatistics = () => {
   totalTasksCount.textContent = tasks.length;
   const completedTasks = tasks.filter(task => task.completed);
   completedTasksCount.textContent = completedTasks.length;
   incompleteTasksCount.textContent = tasks.length - completedTasks.length;
 };

 // 事件监听器
 addTaskButton.addEventListener('click', addTask);
 searchInput.addEventListener('input', renderTasks);
 sortSelect.addEventListener('change', renderTasks);
 changeThemeButton.addEventListener('click', changeTheme);

 // 加载任务
 loadTasks();